<template>
  <div class="app-container">
    <h2 class="con-title">商品库存导入</h2>
    <div class="btn-box">
      <div style="float:right;">
        <el-button type="primary" size="mini" @click="leading">导入商品库存</el-button>
        <el-dialog title="提示" :visible.sync="dialogVisible" width="580px" center>
          <el-upload class="upload" ref="upload" action="submitUrl" :limit="1" :auto-upload="false" :before-upload="beforeUpload" :disabled="flag" accept=".xls,.xlsx">
            <el-button size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">请严格按照模板格式上传文件，文件格式为.xls或.xlsx</div>
          </el-upload>
          <div class="input-inline" style="margin-top:20px;">
            文件标题：
            <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="标题字数限制0-50字" v-model="fileTitle" class="textareaClass">
            </el-input>
          </div>
          <div class="explain">
            <p>说明</p>
            <p>1、文件标题将以“货源更新动态“的形式在头号买手平台展示。</p>
            <p>2、文件标题参考样式：</p>
            <p>
              <span>①天津现货渠道年中折扣专场。</span>
            </p>
            <p>
              <span>②2018重点渠道推荐款，现货首发。</span>
            </p>
            <p>
              <span>③adidas、nike 32款新品，采购价低至5.8折。</span>
            </p>
            <p>3、商品标题不能出现企业名称、供应商仓库等企业信息。</p>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitUpload" :loading="uploadLoading">确 定</el-button>
            <el-button @click="clearUploadedFile">取 消</el-button>
          </span>
        </el-dialog>
        <el-button type="primary" icon="el-icon-download" size="mini" @click="tmpDownload" :loading="downloadLoading">导入模板下载</el-button>
      </div>
    </div>
    <div class="source">
      <div class="input-line">
        <div class="input-inline">
          <label class="input-label">商品货号：</label>
          <div class="el-input" style="width:180px">
            <input type="text" autocomplete="off" placeholder="请输入内容" class="el-input__inner" v-model="listQuery.goodsCode">
          </div>
        </div>
        <div class="input-inline">
          <label class="input-label">品牌：</label>
          <div class="el-input" style="width:180px">
            <input type="text" autocomplete="off" placeholder="请输入内容" class="el-input__inner" v-model="listQuery.brandName">
          </div>
        </div>
        <div class="input-inline">
          <label class="input-label">库存状态：</label>
          <div class="el-input" style="width:180px">
            <el-select v-model="listQuery.stockStatus" clearable placeholder="请选择">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="input-inline">
          <label class="input-label">上传时间：</label>
          <div class="el-input" style="width:180px">
            <el-date-picker v-model="listQuery.startDate" type="date" placeholder="选择日期" :picker-options="pickerOptions1" value-format="yyyy-MM-dd">
            </el-date-picker>
          </div>
          <div class="form-mid">-</div>
          <div class="el-input" style="width:180px">
            <el-date-picker v-model="endDate" type="date" placeholder="选择日期" :picker-options="pickerOptions2" value-format="yyyy-MM-dd">
            </el-date-picker>
          </div>
        </div>
      </div>
      <el-button type="primary" icon="el-icon-search" style="position: absolute;top:20px;right:20px;" size="small" @click="searchSubmit">搜索</el-button>
    </div>
    <div class="btn-box">
      <div>
        <el-button type="primary" size="mini" @click="upper">批量上架</el-button>
        <el-button type="primary" size="mini" @click="lower">批量下架</el-button>
        <el-button type="primary" icon="el-icon-download" size="mini" @click="exportGoodsStock" :loading="downloadLoading">批量下载库存</el-button>
      </div>
    </div>
    <el-table :data="list" ref="tableData" v-loading.body="listLoading" stripe element-loading-text="Loading" border highlight-current-row @row-click="rowChecked" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column align="center" label='商品货号' min-width="140px">
        <template slot-scope="scope">
          {{scope.row.goodsCode}}
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center">
        <template slot-scope="scope">
          {{scope.row.brandName}}
        </template>
      </el-table-column>
      <el-table-column label="商品尺码" align="center">
        <template slot-scope="scope">
          {{scope.row.sizeName}}
        </template>
      </el-table-column>
      <el-table-column align="center" label='条形码' min-width="125px">
        <template slot-scope="scope">
          {{scope.row.sku}}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="市场价（元）">
        <template slot-scope="scope">
          <span>{{scope.row.goodsPrice | formatMoney}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="销售价（元）">
        <template slot-scope="scope">
          <span>{{scope.row.goodsMoney | formatMoney}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label='折扣'>
        <template slot-scope="scope">
          {{scope.row.goodsDiscount}}
        </template>
      </el-table-column>
      <el-table-column align="center" label='导入库存量'>
        <template slot-scope="scope">
          {{scope.row.stockNum}}
        </template>
      </el-table-column>
      <el-table-column align="center" label='更新时间' min-width="155px">
        <template slot-scope="scope" v-if="scope.row.updateDate!=null">
          <!--<i class="el-icon-time"></i>-->
          {{scope.row.updateDate| formatDate( 'yyyy-MM-dd hh:mm')}}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="状态" align="center">
        <template slot-scope="scope">
          <span class="success" v-if="scope.row.stockStatus == 1">上架</span>
          <span class="danger" v-else>下架</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="scope">
          <el-button v-if="scope.row.stockStatus!='1'" size="mini" type="success" @click="handleModifyStatus(scope.row,'1')">上架
          </el-button>
          <el-button v-if="scope.row.stockStatus!='0'" size="mini" type="danger" @click="handleModifyStatus(scope.row,'0')">下架
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.pageIndex" :page-sizes="[10, 20, 30, 40]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
  </div>
</template>

<script>
import {
  getGoodsList
} from '@/api/list'
import {
  setGoodsStockStatus
} from '@/api/list'
import {
  exportGoodsStock
} from '@/api/list'
// import {
//   exportGoodsStockMB
// } from '@/api/list'
import {
  importGoodsStock
} from '@/api/list'
import {
  getUserInfo
} from '@/api/user'

export default {
  data() {
    return {
      currentPage4: 1,
      total: 100,
      listQuery: {
        pageIndex: 1,
        pageSize: 20,
        goodsCode: '',
        brandName: '',
        stockStatus: null,
        startDate: '',
        endDate: ''
      },
      options: [{
        value: 0,
        label: '下架'
      }, {
        value: 1,
        label: '上架'
      }],
      endDate: '',
      upLower: {
        stockId: '',
        stockStatus: ''
      },
      dialogVisible: false,
      list: null,
      listLoading: true,
      downloadLoading: false,
      uploadLoading: false,
      fileTitle: '',
      flag: false,
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e7
        }
      },
      pickerOptions2: {
        disabledDate: (time) => {
          return time.getTime() < this.value1
        }
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 列表加载
    fetchData() {
      // 结束日期加一天
      if (this.endDate !== '') {
        const date = new Date(this.endDate)
        // 加一天
        const time = date.setDate(date.getDate() + 1)
        // 使用filters 里使用
        this.listQuery.endDate = this.$options.filters.formatDate(time, 'yyyy-MM-dd')
      }
      this.listLoading = true
      getGoodsList(this.listQuery).then(res => {
        this.list = res.data.goodsList
        this.total = res.data.total
        this.listLoading = false
      })
    },
    searchSubmit() {
      this.listQuery.pageIndex = 1
      if (this.listQuery.stockStatus === '') {
        this.listQuery.stockStatus = null
      }
      this.fetchData()
    },
    rowChecked(row, event, column) {
      this.$refs.tableData.toggleRowSelection(row)
    },
    handleSelectionChange(val) {
      const me = this
      this.upLower.stockId = ''
      val.forEach(function(ele) {
        me.upLower.stockId += ele.id + ','
      })
    },
    // 批量上架
    upper() {
      this.upLower.stockStatus = 1
      if (this.upLower.stockId === '') {
        this.$message({
          message: '请选择需要上架的商品',
          type: 'error'
        })
      } else {
        setGoodsStockStatus(this.upLower).then(res => {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.fetchData()
        })
      }
    },
    // 批量下架
    lower() {
      this.upLower.stockStatus = 0
      if (this.upLower.stockId === '') {
        this.$message({
          message: '请选择需要下架的商品',
          type: 'error'
        })
      } else {
        setGoodsStockStatus(this.upLower).then(res => {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.fetchData()
        })
      }
    },
    // 下载商品库存
    exportGoodsStock() {
      this.downloadLoading = true
      exportGoodsStock().then(res => {
        location.href = res.data.fileUrl
        this.downloadLoading = false
        this.$message({
          message: '操作成功',
          type: 'success'
        })
      })
    },
    // 下载库存模板
    tmpDownload() {
      this.downloadLoading = true
      location.href = 'http://img.sportjx.com/img/download/template/stock_template.xlsx'
      setTimeout(() => {
        this.downloadLoading = false
      }, 1000)
      // exportGoodsStockMB().then(res => {
      //   location.href = res.data.fileUrl
      //   this.downloadLoading = false
      //   this.$message({
      //     message: '操作成功',
      //     type: 'success'
      //   })
      // })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.listQuery.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.listQuery.pageIndex = val
      this.fetchData()
    },
    // 上下架
    handleModifyStatus(row, status) {
      this.upLower.stockId = row.id
      this.upLower.stockStatus = status
      setGoodsStockStatus(this.upLower).then(res => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.stockStatus = status
      })
    },
    leading() {
      const date = new Date()
      const myDate = this.$options.filters.formatDate(date, 'yyyy-MM-dd')
      getUserInfo().then(res => {
        if (res.data.uInfo.modifyStaff !== '0' && res.data.uInfo.salType !== '0') {
          this.fileTitle = myDate + res.data.uInfo.uCode + '重点款推荐'
          this.dialogVisible = true
        } else if (res.data.uInfo.modifyStaff === '0') {
          this.$message({
            message: '请完善您的<a href="#/account/warehouse" style="color: #28a3ef;">仓库信息</a>',
            type: 'error',
            dangerouslyUseHTMLString: true
          })
        } else if (res.data.uInfo.salType === '0') {
          this.$message({
            message: '请填写您的<a href="#/account/freight" style="color: #28a3ef;">运费模板</a>',
            type: 'error',
            dangerouslyUseHTMLString: true
          })
        }
      })
    },
    // 上传文件
    submitUpload() {
      if (this.fileTitle === '') {
        this.$message.error('请填写文件标题')
      } else {
        this.$refs.upload.submit()
      }
    },
    beforeUpload(file) {
      // 使用自己的上传方法
      this.flag = true
      this.uploadLoading = true
      const fileData = new FormData() // 创建form对象
      // file 的键要是接口提供的值
      fileData.append('goodsStockFile', file)
      const params = {
        goodsStockFile: encodeURI(file.name),
        fileTitle: encodeURI(this.fileTitle)
      }
      // 上传文件,需要将文件data单独传，签名参数单独传
      importGoodsStock(fileData, params)
        .then(res => {
          this.$message.success(res.info)
          this.dialogVisible = false
          this.flag = false
          this.uploadLoading = false
        }).catch(() => {
          this.flag = false
          this.uploadLoading = false
        })
      return false
    },
    clearUploadedFile() {
      this.$refs.upload.clearFiles()
      this.dialogVisible = false
    }
  }
}

</script>
<style rel="stylesheet/scss" lang="scss">
@import 'src/assets/css/jx-order.scss';
.success {
  color: #67c23a
}

.danger {
  color: #f56c6c
}

.textareaClass {
  display: inline-block;
  width: 445px;
  vertical-align: top
}

.explain {
  color: rgb(0, 153, 255);
  font-size: 12px;
  padding-left: 75px;
}

.explain p {
  margin: 0;
}

.explain p span {
  margin-left: 20px;
}
</style>
